import re
import helpers
import random
import hashlib

tpl = """#include <iostream>
/*directives*/

using namespace std;

/*functions*/

int main(){
/*code*/
    return 0;
}
"""

COMPILE = False

with  open('Questions_tpl/'+'questions_cpp_Errors.cpp') as f:
    examples = f.read()

examples = examples.split('//')
questions = []
answers = []
counter = 0
for ex in examples[1:]:
    title, code = ex.strip(' \t').split('\n', 1)
    #~ print(title, code)
    if ' ' in title:
        msg_type, explanation = title.strip(' \t').split(' ', 1)
    else:
        msg_type = title
        explanation = ''
    msg_types = {'ERR':'Error', 'WARN':'Warning', 'NOTICE':"Notice", "OK":"OK", 'SyntaxOK':'SyntaxOK'}
    answer = msg_types[msg_type] +": "+ explanation
    answer = answer.strip(' :')
    # check if same answer for different question
    if answer in answers:
        title += "_%s"%answers.count(answer)
        #~ print (title)

    answers.append(answer)
    #~ title =  "CppErr_%s_"+str(len(answers)) + title


    ##########
    directives = []  # mostly includes
    
    for lineno, line in enumerate(code.split('\n')):
        if line.lstrip(' \t').startswith('#'):
            directives.append(line.lstrip(' \t'))
    if directives:
        etc, code = code.split(directives[-1])  # chop off directives (if found)
    directives = '\n'.join(directives)  # join list to text

    #########
    functions = ''

    if 'int main' in code:
        functions, code = re.split(r'int main.+\{', code, re.DOTALL)
        code = code[:code.rfind('}')] #remove closing '}' of main
        # dedent
        def dedent(line):
            return line[:4].lstrip(' ') + line[4:]
        code = '\n'.join( [dedent(line) for line in code.split('\n')])

        
    if "/*main*/" in code:
        functions, code = code.split("/*main*/")

    code = code.rstrip('\n ')
    code = '\n'.join( ['    '+line for line in code.split('\n')])

    #########
    full_code = tpl .replace('/*directives*/', directives)\
                    .replace('/*functions*/', functions)\
                    .replace('/*code*/', code)

    # remove multiple empty lines
    full_code = full_code.replace('\n        \n', '\n\n') 
    full_code = full_code.replace('\n    \n', '\n\n') 
    re_multiemptylines = re.compile(r'(\n\s*?)(\n\s*?)(\n *?)+', re.DOTALL) # somehow doesn't work  --- http://regex.powertoy.org/
    re_multiemptylines = re.compile(r'\n\n\n+', re.DOTALL)
    full_code = re_multiemptylines.sub('\n\n', full_code)


    ##################
    counter += 1
    m = hashlib.md5()
    m.update(title.encode('utf8'))

    question = helpers.src_to_GIFT(
                    title,
                    full_code,
                    question_text='Ar/kokia čia yra bėda?',
                    lang_code2img='cpp',
                    title_without_hints=  "Err_"+m.hexdigest()#"Err_%s" %counter
    )
    questions.append(question)
    #~ print("\n\n********", title, '\n\n', full_code)
    #~ print(question)
    


    if COMPILE:
    #~ if True:
        with open('/tmp/a.cpp', 'w' ) as f:
            f.write(full_code)
        print ('\n\n', full_code)
        print('-----------------')
        import subprocess
        out_txt = subprocess.getoutput('g++ -Wall -c /tmp/a.cpp')
        print("---- Compilation output: --------\n", out_txt)
    
        #~ try:
            #~ out_txt = subprocess.check_output(
                #~ ['g++', '-Wall', '-c', '/tmp/a.cpp'],
                #~ stderr=subprocess.STDOUT,
                #~ universal_newlines=True
            #~ )
        #~ except subprocess.CalledProcessError as e:  #(retcode, cmd, output=output)
            #~ print("output", e.output)


## Output stufff

print("\n$CATEGORY: $system$/CPP/ERRORS_2\n") 


for q, a in zip(questions, answers[:]):
    print('\n\n')
    print( q )
    print('{')
    random.shuffle(answers)
    how_many_choices = random.randint(4, min(len(answers), 8)) # at least 4 choices
    for choice in sorted(list(set(answers[:how_many_choices] + [a, 'OK']))):
        print(  '    ', '=' if a==choice else '~',
                helpers.escape_GIFT_spec_chars(choice)
             )
    print('}')

#~ print (len(questions))
